import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { orders, orderItems, customers, products, orderActivities, inventory, inventoryHistory } from '@/lib/schema';
import { eq, and, sql } from 'drizzle-orm';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const resolvedParams = await params;
    const order = await db
      .select({
        id: orders.id,
        customerId: orders.customerId,
        customerName: customers.name,
        customerEmail: customers.email,
        customerPhone: customers.phone,
        customerAddress: customers.address,
        totalAmount: orders.totalAmount,
        status: orders.status,
        createdAt: orders.createdAt,
        updatedAt: orders.updatedAt
      })
      .from(orders)
      .leftJoin(customers, eq(orders.customerId, customers.id))
      .where(eq(orders.id, parseInt(resolvedParams.id)))
      .limit(1);

    if (order.length === 0) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      );
    }

    const items = await db
      .select({
        id: orderItems.id,
        productId: orderItems.productId,
        productName: products.name,
        productPrice: orderItems.price,
        quantity: orderItems.quantity,
        subtotal: orderItems.subtotal
      })
      .from(orderItems)
      .leftJoin(products, eq(orderItems.productId, products.id))
      .where(eq(orderItems.orderId, parseInt(resolvedParams.id)));

    return NextResponse.json({
      ...order[0],
      items
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    return NextResponse.json(
      { error: '获取订单详情失败' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const resolvedParams = await params;
    const body = await request.json();
    
    // 获取当前订单状态
    const [currentOrder] = await db
      .select({ status: orders.status })
      .from(orders)
      .where(eq(orders.id, parseInt(resolvedParams.id)));

    if (!currentOrder) {
      return NextResponse.json(
        { error: '订单不存在' },
        { status: 404 }
      );
    }

    // 状态转换验证
    if (body.status) {
      const isValidTransition = validateStatusTransition(currentOrder.status, body.status);
      if (!isValidTransition) {
        return NextResponse.json(
          { error: `无法从${getStatusText(currentOrder.status)}变更为${getStatusText(body.status)}` },
          { status: 400 }
        );
      }

      // 处理库存联动
      const inventoryResult = await handleInventoryChanges(
        parseInt(resolvedParams.id),
        currentOrder.status,
        body.status
      );

      if (!inventoryResult.success) {
        return NextResponse.json(
          { error: inventoryResult.error },
          { status: 400 }
        );
      }
    }

    // 更新订单
    const updateData: any = {
      status: body.status,
      totalAmount: body.totalAmount,
      updatedAt: sql`(strftime('%s', 'now'))`
    };
    
    // 如果是取消订单且有取消原因，记录原因
    if (body.status === 'cancelled' && body.cancelReason) {
      updateData.cancelReason = body.cancelReason;
    }

    const [updatedOrder] = await db
      .update(orders)
      .set(updateData)
      .where(eq(orders.id, parseInt(resolvedParams.id)))
      .returning();

    // 记录活动日志
    if (body.status && body.status !== currentOrder.status) {
      let description = `订单状态从 ${getStatusText(currentOrder.status)} 变更为 ${getStatusText(body.status)}`;
      
      // 如果是取消订单且有取消原因，在活动记录中添加原因
      if (body.status === 'cancelled' && body.cancelReason) {
        description += `，原因：${body.cancelReason}`;
      }

      await db.insert(orderActivities).values({
        orderId: parseInt(resolvedParams.id),
        action: 'status_change',
        fromStatus: currentOrder.status,
        toStatus: body.status,
        description: description,
        performedBy: 'system'
      });
    }

    return NextResponse.json(updatedOrder);
  } catch (error: any) {
    console.error('更新订单失败:', error);
    return NextResponse.json(
      { error: '更新订单失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}

// 状态转换验证函数
function validateStatusTransition(fromStatus: string, toStatus: string): boolean {
  const validTransitions: Record<string, string[]> = {
    pending: ['paid', 'cancelled'],
    paid: ['shipped', 'cancelled'],
    shipped: ['delivered'],
    delivered: [],
    cancelled: []
  };

  return validTransitions[fromStatus]?.includes(toStatus) || false;
}

// 状态文本映射
function getStatusText(status: string): string {
  const statusMap: Record<string, string> = {
    'pending': '待支付',
    'paid': '已支付',
    'shipped': '已发货',
    'delivered': '已交付',
    'cancelled': '已取消'
  };
  return statusMap[status] || status;
}

// 库存处理函数
async function handleInventoryChanges(
  orderId: number,
  fromStatus: string,
  toStatus: string
): Promise<{ success: boolean; error?: string }> {
  try {
    // 获取订单商品明细
    const items = await db
      .select({
        productId: orderItems.productId,
        quantity: orderItems.quantity
      })
      .from(orderItems)
      .where(eq(orderItems.orderId, orderId));

    for (const item of items) {
      // 支付时锁定库存
      if (fromStatus === 'pending' && toStatus === 'paid') {
        await lockInventory(item.productId, item.quantity, orderId);
      }
      
      // 发货时扣减实际库存
      if (fromStatus === 'paid' && toStatus === 'shipped') {
        await deductInventory(item.productId, item.quantity, orderId);
      }
      
      // 取消订单时释放库存
      if (toStatus === 'cancelled' && fromStatus !== 'cancelled') {
        await releaseInventory(item.productId, item.quantity, orderId, fromStatus);
      }
    }

    return { success: true };
  } catch (error: any) {
    console.error('库存处理失败:', error);
    return { success: false, error: '库存处理失败: ' + error.message };
  }
}

async function lockInventory(productId: number, quantity: number, orderId: number) {
  const [currentInventory] = await db
    .select({ quantity: inventory.quantity })
    .from(inventory)
    .where(eq(inventory.productId, productId));

  // 如果库存记录不存在，创建一个
  if (!currentInventory) {
    await db.insert(inventory).values({
      productId,
      quantity: 0,
      lowStockThreshold: 10
    });
    throw new Error(`产品库存不存在或库存为0，无法锁定 ${quantity} 件库存`);
  }

  if (currentInventory.quantity < quantity) {
    throw new Error(`产品库存不足，当前库存: ${currentInventory.quantity}, 需要: ${quantity}`);
  }

  // 锁定库存（实际库存不变，但可用库存减少）
  await db
    .update(inventory)
    .set({ quantity: currentInventory.quantity - quantity })
    .where(eq(inventory.productId, productId));

  // 记录库存历史
  await db.insert(inventoryHistory).values({
    productId,
    type: 'out',
    quantity,
    previousQuantity: currentInventory.quantity,
    newQuantity: currentInventory.quantity - quantity,
    notes: `订单 #${orderId} 支付锁定库存`,
    createdBy: 'system'
  });
}

async function deductInventory(productId: number, quantity: number, orderId: number) {
  // 发货时实际库存已经在支付时锁定，这里只需记录
  await db.insert(inventoryHistory).values({
    productId,
    type: 'out',
    quantity,
    notes: `订单 #${orderId} 发货扣减库存`,
    createdBy: 'system'
  });
}

async function releaseInventory(productId: number, quantity: number, orderId: number, fromStatus: string) {
  const [currentInventory] = await db
    .select({ quantity: inventory.quantity })
    .from(inventory)
    .where(eq(inventory.productId, productId));

  // 只有支付状态的订单取消时需要恢复库存
  if (fromStatus === 'paid') {
    await db
      .update(inventory)
      .set({ quantity: currentInventory.quantity + quantity })
      .where(eq(inventory.productId, productId));

    await db.insert(inventoryHistory).values({
      productId,
      type: 'in',
      quantity,
      previousQuantity: currentInventory.quantity,
      newQuantity: currentInventory.quantity + quantity,
      notes: `订单 #${orderId} 取消，释放锁定库存`,
      createdBy: 'system'
    });
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const resolvedParams = await params;
    await db
      .delete(orderItems)
      .where(eq(orderItems.orderId, parseInt(resolvedParams.id)));
    
    await db
      .delete(orders)
      .where(eq(orders.id, parseInt(resolvedParams.id)));

    return NextResponse.json({ message: '订单删除成功' });
  } catch (error: any) {
    console.error('删除订单失败:', error);
    return NextResponse.json(
      { error: '删除订单失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}